//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package indi.qing.controller;
import java.util.Date;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import indi.qing.entity.Device;
import indi.qing.entity.SubDevice;
import indi.qing.service.DeviceService;
import indi.qing.service.SubDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PushReceiver {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private SubDeviceService subService;

    @PostMapping("/api/messageReceiver")
    public ResponseEntity pushReceiver(@RequestBody String jsonString) throws Exception {
        JSONObject deviceData = JSONObject.parseObject(jsonString);
        if ("device.property".equals(deviceData.getString("resource"))) {
            JSONObject notify_data = deviceData.getJSONObject("notify_data");
            JSONObject header = notify_data.getJSONObject("header");
            JSONObject body = notify_data.getJSONObject("body");
            String deviceSn = header.getString("device_id");
            Device device = deviceService.getOne(new QueryWrapper<Device>().lambda().eq(Device::getDeviceSn, deviceSn));
            if(ObjectUtils.isEmpty(device)){
                device = new Device();
                device.setDeviceSn(deviceSn);
                device.setState(1);
                deviceService.save(device);
            }
            JSONArray services = body.getJSONArray("services");
            for (int i = 0; i < services.size(); i++) {
                JSONObject service = services.getJSONObject(i);
                String serviceSn = service.getString("service_id");
                JSONObject properties = service.getJSONObject("properties");
                Integer luminance = properties.getInteger("luminance");
                String substring = serviceSn.substring(0, 5);
                Long typeId;
                if ("Light".equals(substring))  typeId =1L;
                else typeId = 2L;
                SubDevice subDevice = new SubDevice();
                subDevice.setSubSn(serviceSn);
                subDevice.setValue(luminance);
                subDevice.setTypeId(typeId);
                subDevice.setDeviceId(device.getDeviceId());
                subService.save(subDevice);
            }

        }
        return new ResponseEntity(HttpStatus.OK);
    }

}

